# -*- coding: utf-8 -*-

import datetime
import logging

from django.core.mail import send_mail
from django.http import Http404, HttpResponseRedirect, HttpResponse
from django.shortcuts import render, render_to_response

from brand.forms import ContactForm
from brand.models import Brand

logger = logging.getLogger(__name__)        # 应该是需要配置日志的相关信息，才能打印出来

# Create your views here.


def index(request):
    brand_list = Brand.objects.all()

    logger.info('记录日志开始')

    values = request.META.items()

    form = ContactForm(initial={"subject": '请输入标题', 'email': 'email@.xxx.com'})

    context = {
        'name': 'YCSnail',
        'age': 22,
        'brandList': brand_list,
        'req': values,
        'form': form
    }

    logger.debug('记录日志结束')
    return render_to_response('brand/index.html', context)


def time(request, offset):
    try:
        offset = int(offset)
    except ValueError:
        raise Http404()

    now = datetime.datetime.now(),
    # dt = now + datetime.timedelta(hours=offset)
    dt = datetime.datetime.now() + datetime.timedelta(hours=offset)

    return render(request, 'brand/time.html', {
        'offset': '%s' % offset,
        'now': '%s' % now,
        'now_d': datetime.datetime.now(),
        'time': '%s' % dt,
        'str': str(type(datetime.datetime.now()))

    })


def search(request):
    if 'q' in request.GET:
        q = request.GET.get('q', '')

    brand_list = Brand.objects.filter(brand_name_en__contains=q)

    return render_to_response('brand/index.html', {
        'brandList': brand_list,
        'query': q,
    })


def contact(request):
    errors = []
    if request.method == 'POST':
        form = ContactForm(request)
        if form.is_valid():
            cd = form.cleaned_data
            try:
                send_mail(
                    cd['subject'],
                    cd['message'],
                    cd.get('email', 'default@email.com'),
                    ['liyc@zhongsou.com', '461148124@qq.com'],
                )
                print('send email success!!!!!!!!!!!!')
                return HttpResponseRedirect('/brand/contact/thanks')

            except Exception:
                errors.append('send email failure!')
                print('send email failure!!!!!!!!!!!!')
            else:
                pass
            finally:
                form = ContactForm()
    else:
        form = ContactForm()

        print (form.as_p())

    return render_to_response('brand/index.html', {
        'form': form
    })


def contactThanks(request):

    # return render_to_response('brand/thanks.html', {})
    return HttpResponse("It' success. Thank you!")
